<script>
	import {
		uploadApp,
		taskCacheList,
		clearTaskCache,
		offlineUpload,
		checkNetwork,
		getLocation,
	} from '@/request/common.js';
	let isAddress = false;
	export default {
		onLaunch() {
			console.log('App Launch');
			// 检测更新
			uploadApp();
			// 缓存任务
			uni.$on('Task-Cache', (data) => {
				if (data.type === 1) {
					taskCacheList(data.subPlanId);
				} else {
					clearTaskCache();
				}
			});

			// 隔天清空缓存
			let offline = uni.getStorageSync('offline-task-list');
			if (offline && offline.date) {
				let todayStart = new Date(new Date().setHours(0, 0, 0, 0)).getTime();
				let cacheTime = new Date(offline.date).getTime();
				if (todayStart > cacheTime) {
					clearTaskCache();
				}
			}
			// 监听网络变化
			uni.onNetworkStatusChange((res) => {
				isAddress = false;
				if (res.isConnected && res.networkType != 'none') {
					uni.$uv?.throttle(async () => {
						this.startOffilineUpload();
						const local = await getLocation();
						if (!isAddress) {
							isAddress = true;
							offlineUpload(local);
						}
					}, 1000); // 设置适当的延迟
				}
				let network;
				if (['2g', '3g', 'unknown', 'none'].includes(res.networkType)) {
					network = 'none';
				} else {
					network = res.networkType;
				}
				uni.$emit('network-change', network);
			});
		},
		onShow() {
			console.log('App Show');
			// 进入检测网络
			checkNetwork().then((network) => {
				if (network != 'none') {
					offlineUpload();
				}
			});
		},
		onHide() {
			console.log('App Hide');
		},
		onUnload() {
			uni.offNetworkStatusChange();
		},
		methods: {
			startOffilineUpload() {
				setTimeout(() => {
					if (!isAddress) {
						let text = '定位获取失败';
						offlineUpload(text);
						isAddress = true;
					}
				}, 5 * 1000);
			},
		},
	};
</script>

<style>
	/*每个页面公共css */
</style>